package com.feng.zhihao.apigeteway.util;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Map;
import java.util.Set;

import org.apache.commons.beanutils.BeanUtils;

import com.feng.zhihao.apigeteway.ApiGetewayApplication;
import com.feng.zhihao.apigeteway.entity.ChannelInfo;

public class BeanUtil {

	public static Object getBean(String beanName){
		return ApiGetewayApplication.applicationContext.getBean(beanName);
	}
	
	public static void cleanArray(Collection<?> item,int ci){
		cleanArrayc(item,ci,0);
	}
	public static void cleanArrayc(Collection<?> item,int ci,int i){
		for (Object o : item) {
			if(isEntity(o)){
				cleanc(o,ci,i+1);
			}else if( o instanceof Set){
				cleanArrayc((Collection<?>)o,ci,i+1);
			}
		}
	}
	public static void clean(Object o,int ci){
		cleanc(o,ci,1);
	}
	static ThreadLocal<Integer> i=new ThreadLocal<Integer>();
	public static void cleanc(Object o,int ci,int i){
		try {
			Map<String, java.beans.PropertyDescriptor> map=com.xiaoleilu.hutool.util.BeanUtil.getPropertyDescriptorMap(o.getClass(), false);
			for (String k : map.keySet()) {
				if("class".equals(k) || "empty".equals(k)){
					continue;
				}
				try {
					Object v = null;
					try {
						v = invoke(o, "get"+upperCaseFirstLatter(k));
					} catch (Exception e) {
						e.printStackTrace();
					}
					if(v == null){
						continue;
					}
					if(i >= ci){
						try {
							if(isEntity(v)){
								BeanUtils.setProperty(o, k, null);
							}else if(v instanceof Set){
								BeanUtils.setProperty(o, k, null);
							}
						} catch (IllegalAccessException | InvocationTargetException e) {
							e.printStackTrace();
						}
						continue;
					}	
					if(isEntity(v)){
						cleanc(v,ci,i+1);
					}else if(v instanceof Set){
						cleanArrayc((Collection<?>)v,ci,i+1);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		} catch (IntrospectionException e) {
			e.printStackTrace();
		}
	}
	public static String upperCaseFirstLatter(String str){  
	    char[] strChar=str.toCharArray();  
	    strChar[0]-=32;  
	    return String.valueOf(strChar);  
	}  
	public static Object invoke(Object o,String methodName) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		Class<?> clazz = o.getClass(); 
		Method m1=null;
		try {
			m1 = clazz.getDeclaredMethod(methodName);
		} catch (Exception e) {
			System.err.println(methodName);
		}
		return m1.invoke(o);
	}
	public static boolean isEntity(Object o){
		if(o.getClass().getName().startsWith("com.feng.zhihao.apigeteway.entity")){
			return true;
		}else{
			return false;
		}
	}
	public static void main(String[] args) throws Exception {
		System.out.println(ChannelInfo.class.getName());
	}

}
